<template>
  <div class="compontent-img-upload">
    <el-upload
      action="https://fileapi.instrument.com.cn/upflash/upimg.ashx?colname=webinar"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handlePicSuccess"
      :before-upload="beforePicUpload"
      :limit="limit"
      :file-list="getEditImg"
      :class="picList.length >= limit ? 'noImgBorder' : ''"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: {
    image: {
      type: String
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      Pic: '',
      picList: [],
      uid: Math.floor(Math.random() * 100),
      getEditImg: []
    }
  },
  watch: {
    image(val) {
      if (val === 'https://img1.17img.cn/17img') {
        return false
      }
      this.changeImg(val)
    }
  },
  mounted() {
    if (this.image) {
      this.changeImg(this.image)
    }
    this.dialogImageUrl = ''
  },
  methods: {
    changeImg(val) {
      this.picList = []
      this.getEditImg = [{ url: val }]
      const imgObj = {
        uid: this.uid,
        url: this.getEditImg[0].url
      }
      this.picList.push(JSON.parse(JSON.stringify(imgObj)))
    },
    handleRemove(file, fileList) {
      for (let i = 0; i < this.picList.length; i++) {
        if (file.url === this.picList[i].url) {
          this.$emit('imgListDelete', i)
          this.picList.splice(i, 1)
        } else
        if (file.uid === this.picList[i].uid) {
          this.$emit('imgListDelete', i)
          this.picList.splice(i, 1)
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handlePicSuccess(res) {
      const imgObj = {
        uid: this.uid,
        url: res.url
      }

      this.$emit('imgListSucenss', imgObj)
      this.picList.push(JSON.parse(JSON.stringify(imgObj)))
    },
    beforePicUpload(file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!')
      }
      this.uid = file.uid
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.noImgBorder .el-upload--picture-card {
  display: none;
}
</style>
<style scoped>
.avatar-uploader >>> .el-upload-list__item {
      transition: none !important;
    }
</style>
